import { nextTick } from 'vue';
import lottie from "lottie-web";
import animationData from '@/assets/lotties/image-loading.json';
import FyImg from "@/components/base/FyImg.vue";

const vImage = {
    mounted(el, binding) {

        const result = el.getAttribute('data-fy-img');
        // console.log('++++))))____', el, result);

        if (binding.value && el.getAttribute('data-fy-img')) {
            const { value } = binding;

            // console.log('v-image-load指令', el, value, animationData);
            
            // 设置父容器为非默认的static，否则子元素的absolute定位会失效
            el.style.position = 'relative';
            // 创建 Lottie 动画容器
            const lottieContainer = document.createElement('div');
            lottieContainer.style.position = 'absolute';
            lottieContainer.style.width = '100%';
            lottieContainer.style.height = '100%';
            lottieContainer.style.top = '0px';
            lottieContainer.style.left = '0px';
            // lottieContainer.style.borderWidth = '2px';
            // lottieContainer.style.borderStyle = 'solid';
            // lottieContainer.style.borderColor = '#ddd';
            // lottieContainer.style.borderRadius = '6px';
            lottieContainer.style.zIndex = 9999;
            lottieContainer.style.backgroundColor = '#f9f9f9';
            el.appendChild(lottieContainer);

            // 加载 Lottie 动画
            const animation = lottie.loadAnimation({
                container: lottieContainer,
                renderer: 'svg',
                loop: true,
                autoplay: true,
                animationData
            });

            // 获取FyImg的子元素img标签
            const childImg = el.querySelector('img');

            // 创建临时图片对象，用于获取图片
            const img = new Image();
            // http://img.mrzym.top/FswlMLf30bR2MeXCgorQSkUQ3ky1
            img.src = "./src/assets/img/article-cover.png";

            img.onload = () => {
                // 图片加载成功后移除 Lottie 动画
                console.log('图片加载成功');
                animation.destroy();
                lottieContainer.remove();
                childImg.src = value;
            };

            img.onerror = () => {
                // 图片加载失败后显示错误图片
                console.log('图片加载失败');
                animation.destroy();
                lottieContainer.remove();
                childImg.src = '@/assets/img/placeholder.png';
            };
        } else {
            console.error('v-image-load指令需要绑定图片地址并且该指令只能用到于FyImg组件');
        }
    } 
};

export default vImage;
